<template>
  <div class="echarts" ref="echartsRef"></div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import * as echarts from 'echarts'
import china from '../assets/china.json'
import { useUserStore } from '../store/user'
import api from '../helper/api'

const userStore = useUserStore();

const props = defineProps({
  // 地图标题
  uid: {
    type: Number,
    default: 1,
  },
  title: {
    type: String,
    default: '同学录地域分布图'
  },
  // 宽度
  width: {
    type: String,
    default: '100%'
  },
  // 高度
  height: {
    type: String,
    default: '100vh'
  },
  // 主要色调
  primaryColor: {
    type: String,
    default: '#38a1db'
  },
  // 边框色
  borderColor: {
    type: String,
    default: '#fff'
  }
})

const echartsRef = ref(null)


let myData = ref(null)
onMounted(() => {

  // 配置选项
  let getOption = () => {
    return {
      backgroundColor: props.primaryColor,
      title: {
        text: props.title,
        left: 'center',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        top: 10,
        bottom: 10,
        width: '1000px',
        height: '500px'
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          if (params.value) {
            // 这里 用的 模板语法 不能用引号
            return `${params.value}个同学在这里`
          }
          return ''
        },
        // formatter: formatter ? formatter : '{b}<br/>{c}',
        borderColor: '#CB000C',
        borderWidth: '1'
      },
      dataRange: {
        // 数值范围对应的 取色
        x: 'left',
        y: 'bottom',
        show: true
      },
      series: [
        {
          type: 'map',
          map: 'china',
          roam: true,
          zoom: 1.4,
          center: [105, 35],
          label: {
            show: false,
            fontSize: 18,
          },
          itemStyle: {
            areaColor: props.primaryColor,
            borderColor: props.borderColor,
            borderWidth: 0.8,
            shadowColor: '#009bd6',
            shadowBlur: 5
          },
          data: myData.value
        }
      ]
    }
  }

  // 这里请求后端
  let refresh = () => {
    setTimeout(() => {
      api.getFriendMap(userStore.id)
        .then(res => {
          let data = res.data['data']
          // 刷新
          myData.value = data
          myChart.setOption(getOption(), true)
        })
        .catch(err => {
          // console.log('出现错误了')
          myChart.setOption(getOption(), true)
        })
    }, 200);

  }
  let myChart = echarts.init(echartsRef.value)
  echarts.registerMap('china', china)
  window.onresize = () => {
    myChart.resize()
  }
  refresh()
})
</script>

<style scoped>
* {
  border: 0;
  margin: 0;
}

.echarts {
  /* border: 1px solid red; */
  width: v-bind(width);
  height: v-bind(height);
  /* background-color: #003e82; */
}
</style>
